from typing import Optional, List

from sqlalchemy.orm import Session
from educate_ai.papers.paper_model import PaperORM
from educate_ai.papers.paper_schema import PaperBase,PaperCreate,PaperUpdate,PaperOut

def create_paper(db: Session, paper: PaperCreate) -> PaperORM:
    """创建新试卷"""
    db_paper = PaperORM(
        title=paper.title,
        choice_count=paper.choice_count,
        fill_count=paper.fill_count,
        short_count=paper.short_count,
        difficulty_range=paper.difficulty_range,
        major=paper.major,
        course=paper.course,
        subject_requirements=paper.subject_requirements,
        question_ids=paper.question_ids,
        total_score=paper.total_score,
        time_limit=paper.time_limit
    )
    db.add(db_paper)
    db.commit()
    db.refresh(db_paper)
    return db_paper

def get_paper(db: Session, paper_id: int) -> Optional[PaperORM]:
    """根据ID查询试卷"""
    return db.query(PaperORM).filter(PaperORM.id == paper_id).first()

def get_papers_by_course(
    db: Session,
    course: str,
    skip: int = 0,
    limit: int = 100
) -> List[PaperORM]:
    """根据课程查询试卷（带分页）"""
    return db.query(PaperORM).filter(PaperORM.course == course).offset(skip).limit(limit).all()

def get_papers_by_major(
    db: Session,
    major: str,
    skip: int = 0,
    limit: int = 100
) -> List[PaperORM]:
    """根据专业查询试卷（带分页）"""
    return db.query(PaperORM).filter(PaperORM.major == major).offset(skip).limit(limit).all()

def update_paper(
    db: Session,
    paper_id: int,
    paper_update: PaperUpdate
) -> Optional[PaperORM]:
    """更新试卷信息"""
    db_paper = get_paper(db, paper_id)
    if not db_paper:
        return None
    # 更新字段（只更新提供的非空字段）
    update_data = paper_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_paper, key, value)
    db.commit()
    db.refresh(db_paper)
    return db_paper

def delete_paper(db: Session, paper_id: int) -> bool:
    """删除试卷"""
    db_paper = get_paper(db, paper_id)
    if not db_paper:
        return False
    db.delete(db_paper)
    db.commit()
    return True